package cn.com.panda;

import static android.content.pm.PackageManager.PERMISSION_GRANTED;
import static android.hardware.Camera.CameraInfo.CAMERA_FACING_BACK;
import static android.hardware.Camera.CameraInfo.CAMERA_FACING_FRONT;
import static android.hardware.Camera.Parameters.FLASH_MODE_AUTO;
import static android.hardware.Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.NinePatch;
import android.graphics.Point;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Display;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.otaliastudios.cameraview.BitmapCallback;
import com.otaliastudios.cameraview.CameraListener;
import com.otaliastudios.cameraview.CameraView;
import com.otaliastudios.cameraview.FileCallback;
import com.otaliastudios.cameraview.PictureResult;
import com.otaliastudios.cameraview.VideoResult;
import com.otaliastudios.cameraview.size.AspectRatio;
import com.otaliastudios.cameraview.size.Size;
import com.otaliastudios.cameraview.size.SizeSelector;
import com.otaliastudios.cameraview.size.SizeSelectors;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.com.panda.base.BaseActivity;
import cn.com.panda.conf.Config;
import cn.com.panda.net.CMApiManager;
import cn.com.panda.net.http.request.HttpRequest;
import cn.com.panda.utils.BitmapUtil;
import cn.com.panda.utils.OssUtils;
import cn.com.panda.utils.PictureUtil;
import cn.com.panda.utils.ToastUtils;
import cn.com.panda.view.camera.GridView;
import cn.com.panda.view.camera.ProgressCameraView;
import cn.com.panda.view.camera.ResizeAbleSurfaceView;
import cn.com.panda.view.dialog.DialogWithProgress;
import cn.com.panda.view.wheelview.WheelViewGroup;

public class CameraActivity extends BaseActivity implements View.OnClickListener{

    private int screenWidth,screenHeight;
    private static TextView fourthree,oneone,team,cancel,ok,btdevice,my,model,ninesixteen,flag,stop;
    private static CameraView camera;
    private FrameLayout.LayoutParams params;
    private static ProgressCameraView capture;
    private int captureCount = 1;
    private RelativeLayout teamparent;
    private HashMap<String,String> teammap = new HashMap<>();
    private WheelViewGroup wheelViewGroup;
    private List<String> teamnames = new ArrayList<>();
    private List<String> teamids = new ArrayList<>();
    private LinearLayout addwheelgroup;
    private String curTeamId ;//当前选中的组织ID
    private String userId;//用户id
    private String curDeviceName;//当前设备名
    private String curDeviceMacaddress;//当前设备mac地址
    private List<File> willUploadfiles = new ArrayList<>();
    private boolean isCaptureing = false;//标识是否在拍照中
    DialogWithProgress dialogWithProgress;
    private StringBuffer pictures_set = new StringBuffer();//上传图片的路径集合
    private int uploadCount = 0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera);

        curTeamId = "187";//假定输入默认teamid
        userId = "16";//假定输入默认userid

        WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        Display display = manager.getDefaultDisplay();
        Log.e("屏幕宽高",display.getWidth()+":"+display.getHeight());

        curDeviceName = getIntent().getExtras().getString("name","");
        curDeviceMacaddress = getIntent().getExtras().getString("mac","");

        screenWidth = 1080;
        screenHeight = 1440;

        if(fourthree == null) {
            fourthree = findViewById(R.id.fourthree);
            fourthree.setOnClickListener(this);
        }
        if(oneone == null) {
            oneone = findViewById(R.id.oneone);
            oneone.setOnClickListener(this);
        }

        if(ninesixteen == null){
            ninesixteen = findViewById(R.id.ninesixteen);
            ninesixteen.setOnClickListener(this);
        }

        btdevice = findViewById(R.id.btdevice);
        btdevice.setText(curDeviceName);
        btdevice.setOnClickListener(this);

        my = findViewById(R.id.my);
        my.setOnClickListener(this);

        stop = findViewById(R.id.stop);
        stop.setOnClickListener(this);

        model = findViewById(R.id.model);
        model.setOnClickListener(this);

        flag = findViewById(R.id.flag);

        if(!isAllowPermission(Manifest.permission.CAMERA))
            requestPermission(this,Manifest.permission.CAMERA);
        else
            initCamera(screenWidth,screenHeight);

        if(!isAllowPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE))
            requestPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE);

        addWheelView();

        changCaptureRatio(0);

    }

    private void addWheelView(){
        if(team == null) {
            team = findViewById(R.id.team);
            team.setOnClickListener(this);
        }
        teamparent = findViewById(R.id.teamparent);
        wheelViewGroup = new WheelViewGroup(this);
        wheelViewGroup.setWheelCount(1);
        //模拟几个组织
        teammap.put("187","一号坑");
        teammap.put("0002","二号坑");
        teammap.put("0003","三号坑");
        teamnames.clear();
        for (String key:teammap.keySet()) {
            teamnames.add(teammap.get(key));
            teamids.add(key);
        }
        wheelViewGroup.showData(wheelViewGroup.getFirstwheelview(),teamnames);
        cancel = findViewById(R.id.cancel);
        cancel.setOnClickListener(this);
        ok = findViewById(R.id.ok);
        ok.setOnClickListener(this);
        addwheelgroup = findViewById(R.id.addwheelgroup);
        addwheelgroup.removeAllViews();
        addwheelgroup.addView(wheelViewGroup);
    }

    /**
     * 初始化摄像头
     *
     */
    private void initCamera(int width,int height) {
        if(camera == null)
            camera = findViewById(R.id.camera);
        camera = findViewById(R.id.camera);
        params = (FrameLayout.LayoutParams) camera.getLayoutParams();
        params.width = width;
        params.height = height;
        camera.setLayoutParams(params);
        camera.setLifecycleOwner(this);
        camera.setPictureMetering(true);
        if(!camera.isFocused()){
            camera.startAutoFocus(camera.getWidth()/2,camera.getHeight()/2);
        }
        camera.addCameraListener(new CameraListener() {
            @Override
            public void onPictureTaken(PictureResult result) {
                // A Picture was taken!
                capture.setCapture(true);
                capture.setProgress(captureCount);

                File directory = mContext.getFilesDir();
                String picname = PictureUtil.picName(curTeamId,captureCount,".jpg");
                result.toFile(new File(directory + "/" + picname), new FileCallback() {
                    @Override
                    public void onFileReady(@Nullable File file) {
                        if(file.exists()){
                            willUploadfiles.add(file);
                        }
                    }
                });

                mHandler.sendEmptyMessage(captureCount==36?1:0);
                if(captureCount < 36)
                    captureCount++;
            }

            @Override
            public void onVideoTaken(VideoResult result) {
            }

        });
        camera.setPictureSize(new SizeSelector() {
            @Override
            public List<Size> select(List<Size> source) {
                // Receives a list of available sizes.
                // Must return a list of acceptable sizes.
                Size size = new Size(screenWidth,screenHeight);
                List<Size> list = new ArrayList<>();
                list.add(size);
                return list;
            }
        });
        if(capture == null)
            capture = findViewById(R.id.capture);
        capture.setMaxProgress(36);
        capture.setOnClickListener(this);

    }

    private void saveAndSend(File file){
        Log.e("camera",file.getAbsolutePath());
        Log.e("camerasize",file.length()/1024/1024+"M");
        int rotation = BitmapUtil.readPictureDegree(file.getAbsolutePath());
        Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
        Bitmap desc = BitmapUtil.rotateBitmapByDegree(bitmap,rotation);
        if(screenHeight == 1080){
            //裁剪
            desc = Bitmap.createBitmap(desc,0,0,screenWidth,screenHeight);
        }
        BitmapUtil.saveBitmapToSDCard(desc,file.getAbsolutePath());
        String ossFileName = OssUtils.getOssFileName(Integer.parseInt(curTeamId), userId,file.getName(),"p");

        CMApiManager.uploadImage(mContext, file.getAbsolutePath(), ossFileName, new HttpRequest.OnResponseLister() {
            @Override
            public void onResponse(Object response) {
                //上传成功
                Log.e("uploadImage",response.toString());
                pictures_set.append(response.toString());
                pictures_set.append(",");
                uploadCount += 1;
                dialogWithProgress.setProgressCurValue(uploadCount);

                showFlagAnimator();

                if(uploadCount <= 35)
                    saveAndSend(willUploadfiles.get(uploadCount));
                else
                    clearData();
            }

            @Override
            public void onError(Object errormsg) {
                //上传失败
                Log.e("uploadImage",errormsg.toString());
                saveAndSend(file);
            }

            @Override
            public void onDownLoad(float progress, long total) {

            }
        });
        bitmap.recycle();
        desc.recycle();
    }

    private void showFlagAnimator(){
        flag.setVisibility(View.VISIBLE);
        ObjectAnimator transAnimator = ObjectAnimator.ofFloat(flag,"translationY",0,-100);
        ObjectAnimator alphaAnimator = ObjectAnimator.ofFloat(flag,"alpha",1,0);

        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.setDuration(500L);
        animatorSet.play(transAnimator).with(alphaAnimator);
        animatorSet.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                flag.setVisibility(View.INVISIBLE);
            }
        });
        animatorSet.start();

    }

    private Handler mHandler = new Handler(){
        public void handleMessage(Message msg) {
            if(msg.what == 0){
                resetOption(false);
            }else if(msg.what == 1){
                captureCount = 1;
                resetOption(true);
                dialogWithProgress = new DialogWithProgress(mContext,R.style.MyDialog);
                dialogWithProgress.setContent("图片上传中，请稍候!");
                dialogWithProgress.setProgressMax(36);
                dialogWithProgress.show();

                dialogWithProgress.setCanceledOnTouchOutside(false);

                saveAndSend(willUploadfiles.get(0));



            }
        }
    };

    @Override
    protected void checkPermissionResult(String[] permissions, int[] grantResults) {
        if(permissions.length > 0 && grantResults.length > 0){
            if(permissions[0].equals(Manifest.permission.CAMERA)){
                if(grantResults[0] != PERMISSION_GRANTED)
                    ToastUtils.showShort(mContext,"未开启相机权限无法拍照");
                else
                    initCamera(screenWidth,screenHeight);
            }
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if(id == R.id.fourthree){
            screenWidth = 1080;
            screenHeight = 1440;
            params.width = screenWidth;
            params.height = screenHeight;
            camera.setLayoutParams(params);
            changCaptureRatio(0);
        }else if(id == R.id.oneone){
            screenWidth = 1080;
            screenHeight = 1080;
            params.width = screenWidth;
            params.height = screenHeight;
            camera.setLayoutParams(params);
            changCaptureRatio(1);
        }else if(id == R.id.ninesixteen){
            screenWidth = 810;
            screenHeight = 1440;
            params.width = screenWidth;
            params.height = screenHeight;
            camera.setLayoutParams(params);
            changCaptureRatio(2);
        }
        else if(id == R.id.capture){
            Size size = camera.getPictureSize();
            camera.takePicture();
        }else if(id == R.id.team){
            teamAnimator(true);
        }else if(id == R.id.ok){
            int index = wheelViewGroup.getFirstChoose();
            team.setText(teamnames.get(index));
            curTeamId = teamids.get(index);
            teamAnimator(false);
        }else if(id == R.id.cancel){
            teamAnimator(false);
        }else if(id == R.id.btdevice){
            Bundle bundle = new Bundle();
            toActivityWithResult(BlueToothActivity.class,bundle,1000);
        }else if(id == R.id.my){
            Bundle bundle = new Bundle();
            bundle.putString("url", Config.mysoft);//我的页面
            toActivity(WebViewActivity.class,bundle);
        }else if(id == R.id.model){
            Bundle bundle = new Bundle();
            bundle.putString("url",Config.instruction_3d);//3D模型页面
            toActivity(WebViewActivity.class,bundle);
        }else if(id == R.id.stop){
            clearData();
        }
    }

    private void changCaptureRatio(int index){
        fourthree.setBackgroundResource(index == 0?R.drawable.online_border:R.drawable.unonline);
        fourthree.setTextColor(index == 0?mContext.getResources().getColor(R.color.capture_btn_bg):mContext.getResources().getColor(R.color.radiotext));

        oneone.setBackgroundResource(index == 1?R.drawable.online_border:R.drawable.unonline);
        oneone.setTextColor(index == 1?mContext.getResources().getColor(R.color.capture_btn_bg):mContext.getResources().getColor(R.color.radiotext));

        ninesixteen.setBackgroundResource(index == 2?R.drawable.online_border:R.drawable.unonline);
        ninesixteen.setTextColor(index == 2?mContext.getResources().getColor(R.color.capture_btn_bg):mContext.getResources().getColor(R.color.radiotext));
    }

    private void teamAnimator(boolean isShow){
        ObjectAnimator objectAnimator;
        if(isShow){
            objectAnimator = ObjectAnimator.ofFloat(teamparent,"translationY",-teamparent.getHeight(),0);
        }else{
            objectAnimator = ObjectAnimator.ofFloat(teamparent,"translationY",0,-teamparent.getHeight());
        }
        objectAnimator.setDuration(300);
        objectAnimator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                teamparent.setVisibility(isShow?View.VISIBLE:View.INVISIBLE);
            }
        });
        objectAnimator.start();
    }

    private void clearData(){
        captureCount = 1;
        resetOption(true);
        willUploadfiles.clear();
        isCaptureing = false;
        pictures_set.delete(0,pictures_set.length()-1);
        uploadCount = 0;
    }

    private void resetOption(boolean enable){
        team.setEnabled(enable);
        btdevice.setEnabled(enable);
        my.setEnabled(enable);
        model.setEnabled(enable);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case 1000:
                if(resultCode == RESULT_OK){
                    curDeviceName = getIntent().getExtras().getString("name","");
                    curDeviceMacaddress = getIntent().getExtras().getString("mac","");
                    btdevice.setText(curDeviceName);
                    clearData();
                }
                break;
            default:
                break;
        }
    }
}